package com.ruoyi.web.controller.persona;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.ReceivedMessage;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.smartai.domain.FansContent;
import com.ruoyi.smartai.domain.FansUtil;
import com.ruoyi.smartai.service.IDialogueService;
import com.ruoyi.smartai.service.IFansUtilService;
import com.ruoyi.system.domain.FansInfo;
import com.ruoyi.system.domain.smartai.ScenarioData;
import com.ruoyi.system.domain.smartai.ScenarioDataUtils;
import com.ruoyi.system.service.IFansInfoService;
import com.ruoyi.web.controller.webSocket.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/persona/smart")
public class SmartAIController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(FansInfoController.class);

    @Autowired
    private IDialogueService iDialogueService;

    @Autowired
    private IFansInfoService iFansInfoService;


    @Autowired
    private IFansUtilService fansUtilService;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired(required = false)
    RedisCache redisCache;

    @Value("${devicesPath.customerFile}")
    private String customerFile;

    @PostMapping("/chat")
    @Anonymous
    public AjaxResult receiveMessages(@Validated @RequestBody ReceivedMessage receivedMessage) {
        log.info("----------------  autoChat smart receiveMessages-------------------");
        FansInfo info = iFansInfoService.selectChatByClientNumber(receivedMessage.getFromNumber());
        if (StringUtils.isNull(info)) {
            return error(receivedMessage.getFromNumber() + " 不是粉丝");
        }
        CompletableFuture.runAsync(() -> {
            try {
                receivedMessage.setTimestamp(DateUtils.dateTime());
                receivedMessage.setUserType(1);
                receivedMessage.setType("chat");
                String key = "persona:fans:" + receivedMessage.getFromNumber() + ":unread";
                int unread = 1;
                if (redisCache.hasKey(key)) {
                    unread = redisCache.getCacheObject(key);
                    unread += 1;
                    redisCache.setCacheObject(key, unread);
                } else {
                    redisCache.setCacheObject(key, unread);
                }
                webSocketServer.setMessage(receivedMessage.getToNumber(), receivedMessage);
            } catch (Exception e) {
                log.error("发送消息到前端失败：" + e);
            }
        });

        iDialogueService.combinationMessage(receivedMessage);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", 1);
        return ajax;
    }

    /**
     * 发送图片消息
     */
    @Log(title = "上传图片", businessType = BusinessType.UPDATE)
    @PostMapping("/sendImage")
    public AjaxResult sendImage(@RequestPart("imageFile") MultipartFile imageFile) throws IOException, InvalidExtensionException {
        if (!imageFile.isEmpty()) {
            String avatar = FileUploadUtils.uploadImage(customerFile, imageFile, MimeTypeUtils.IMAGE_EXTENSION);
            AjaxResult ajax = AjaxResult.success();
            log.info("保存媒体资源成功：" + avatar);
            ajax.put("imgUrl", avatar);
            return ajax;
        }
        return error("上传图片异常，请联系管理员");
    }

    /**
     * 获取通用设置
     */
    @Log(title = "获取通用设置", businessType = BusinessType.UPDATE)
    @GetMapping("/fansUtil")
    public AjaxResult fansUtil() {
        return success(fansUtilService.getFansUtil());
    }

    @Log(title = "更新通用设置", businessType = BusinessType.UPDATE)
    @PostMapping("/updateFansUtil")
    public AjaxResult updateFansUtil(@Validated @RequestBody FansUtil fansUtil) {
        log.info("--------------");
        return success(fansUtilService.updateFansUtil(fansUtil));
    }

    @Log(title = "粉丝信息分析", businessType = BusinessType.UPDATE)
    @GetMapping("/fanAnalysis")
    @Anonymous
    public AjaxResult fanAnalysis(@RequestParam("fansNumber") String fansNumber, @RequestParam("customerNumber") String customerNumber) {
        FansContent fansContent = fansUtilService.fanAnalysis(fansNumber, customerNumber);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", fansContent);
        return ajax;
    }

    @Log(title = "更新通用设置", businessType = BusinessType.UPDATE)
    @PostMapping("/saveScenario")
    public AjaxResult saveScenario(@Validated @RequestBody ScenarioData scenario) {
        log.info("------saveScenario--------");
        return success(ScenarioDataUtils.saveScenario(scenario));
    }

    @Log(title = "获取通用设置", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/{customerNumber}")
    public AjaxResult getScenario(@PathVariable("customerNumber") String customerNumber) {
        log.info("------getScenario--------");
        return success(ScenarioDataUtils.getScenario(customerNumber));
    }



}
